import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, message } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { getDepartmentList, createDepartment, updateDepartment, deleteDepartment } from '../../../services/api';

const DepartmentList = () => {
  const [departments, setDepartments] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingDepartment, setEditingDepartment] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 8,
    total: 0,
  });

  const fetchDepartments = async () => {
    setLoading(true);
    try {
      const response = await getDepartmentList();
      if (response.code === 200 && Array.isArray(response.data)) {
        setDepartments(response.data);
        setPagination(prev => ({
          ...prev,
          total: response.data.length
        }));
      } else {
        setDepartments([]);
        setPagination(prev => ({
          ...prev,
          total: 0
        }));
        message.error(response.message || '获取部门列表失败');
      }
    } catch (error) {
      console.error('获取部门列表失败:', error);
      message.error('获取部门列表失败');
      setDepartments([]);
      setPagination(prev => ({
        ...prev,
        total: 0
      }));
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchDepartments();
  }, []);

  const handleAdd = () => {
    setEditingDepartment(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record) => {
    console.log('点击编辑按钮，当前记录:', record);
    setEditingDepartment(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个部门吗？如果部门下还有用户，将无法删除。',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await deleteDepartment(id);
          if (response.code === 200) {
            message.success('删除成功');
            fetchDepartments();
          } else {
            if (response.message && response.message.includes('foreign key constraint fails')) {
              message.error('该部门下还有用户，无法删除');
            }
            fetchDepartments();
          }
        } catch (error) {
          console.error('删除失败:', error);
          message.error('该部门下还有用户，无法删除');
          fetchDepartments();
        }
      },
    });
  };

  const handleSubmit = async () => {
    console.log('handleSubmit 开始执行');
    try {
      console.log('准备验证表单字段');
      const values = await form.validateFields();
      console.log('表单验证通过，获取的值:', values);
      console.log('当前编辑状态:', editingDepartment);
      
      if (editingDepartment) {
        console.log('准备更新部门，参数:', editingDepartment.depId, values);
        const response = await updateDepartment(editingDepartment.depId, values);
        console.log('更新部门响应:', response);
        if (response.code === 200) {
          message.success('更新成功');
          setModalVisible(false);
          fetchDepartments();
        } else {
          message.error(response.message || '更新失败');
        }
      } else {
        const response = await createDepartment(values);
        if (response.code === 200) {
          message.success('创建成功');
          setModalVisible(false);
          fetchDepartments();
        } else {
          message.error(response.message || '创建失败');
        }
      }
    } catch (error) {
      console.error('操作失败:', error);
      message.error('操作失败');
    }
  };

  const handleTableChange = (newPagination) => {
    setPagination(newPagination);
  };

  const columns = [
    {
      title: '部门ID',
      dataIndex: 'depId',
      key: 'depId',
    },
    {
      title: '部门名称',
      dataIndex: 'depName',
      key: 'depName',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            type="primary"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.depId)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ position: 'relative', minHeight: '100vh', padding: '20px' }}>
      {/* 背景图片层 */}
      <div style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundImage: 'url(/assets/year.png)',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
        opacity: 0.8,
        zIndex: 0,
        pointerEvents: 'none'
      }} />

      {/* 内容层 */}
      <div style={{ 
        position: 'relative', 
        zIndex: 1,
        background: 'rgba(255, 255, 255, 0.9)',
        padding: '24px',
        borderRadius: '12px',
        boxShadow: '0 2px 12px rgba(0,0,0,0.1)'
      }}>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center',
          marginBottom: '24px'
        }}>
          <h2 style={{ margin: 0 }}>部门管理</h2>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            添加部门
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={departments}
          loading={loading}
          rowKey="depId"
          pagination={pagination}
          onChange={handleTableChange}
          style={{ 
            background: 'white',
            borderRadius: '8px',
            overflow: 'hidden'
          }}
        />
      </div>

      <Modal
        title={editingDepartment ? '编辑部门' : '添加部门'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="depId"
            label="部门ID"
            rules={[{ required: true, message: '请输入部门ID' }]}
          >
            <Input disabled={!!editingDepartment} />
          </Form.Item>
          <Form.Item
            name="depName"
            label="部门名称"
            rules={[{ required: true, message: '请输入部门名称' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DepartmentList; 